/*
 * create:2016年4月8日 上午9:52:47
 * author:wangds  
 */
package com.cxkj.shop.utils;

import java.util.Collection;

import com.cxkj.shop.proc.DefaultSelectListMybatisProc;
import com.cxkj.shop.proc.DefaultSelectOneMybatisProc;
import com.cxkj.shop.proc.DefaultUpdateMybatisProc;

import net.wangds.common.context.BeanContext;
import net.wangds.common.context.BeanContextFactory;
import net.wangds.precasting.context.Constants;
import net.wangds.utilities.lang.StringUtils;

/**
 * .
 * 
 * @author wangds
 *
 */
public abstract class AbstractBusinessUtils {


  protected static final Object ORDER_ID_LOCK = new Object();
  protected static long count = 0;
  
  public static BeanContext getContext() {
    return BeanContextFactory.getBeanContext(Constants.SCHEMA_SPRING_PROVIDER);
  }

  protected static <P> boolean execUpdateSql(String sqlId,P param){
    boolean res = false;
    BeanContext ctx = getContext();
    DefaultUpdateMybatisProc<P> proc = ctx.getBean("defaultUpdateMybatis");
    int sql_res = -1;
    try {
      proc.setParameter(param);
      proc.setSqlId(sqlId);
      proc.process();
      sql_res = proc.getResult();
    } finally {
      res = 1==sql_res;
    }
    return res;
  }
  
  protected static <P,T> T execSelectOne(String sqlId, P param){
    BeanContext ctx = getContext();
    DefaultSelectOneMybatisProc<P, T> proc = ctx.getBean("defaultSelOneMybatis");
    proc.setParameter(param);
    proc.setSqlId(sqlId);
    proc.process();
    return proc.getResult();
  }
  
  protected static <P,T> Collection<T> execSelectList(String sqlId, P param){
    BeanContext ctx = getContext();
    DefaultSelectListMybatisProc<P, T> proc = ctx.getBean("defaultSelListMybatis");
    proc.setSqlId(sqlId);
    proc.setParameter(param);
    proc.process();
    return proc.getResult();
  }
  
  /**
   * .
   * 
   * @author wangds 2016年4月15日 下午5:43:07.
   * @return
   */
  public static String newOrderId() {
    String res = "";
    synchronized (ORDER_ID_LOCK) {
      count++;
      res = StringUtils.join(Long.toHexString(System.currentTimeMillis()), Long.toHexString(count));
      if (count % 999 == 0) {
        count = 0;
      }
    }
    return res;
  }
}
